/***********************************************************************
* Copyright 2020 客户公司名称
* @URL: 客户公司网址
* @ProjectName: test
* @Description: 新建，修改，删除，商机产品时，需要汇总商机产品金额到对应的客户下。
* Modification Log :
------------------------------------------------------------------------
* Developer                   Date                   Description
* ----------------------------------------------------------------------
* 陈秋雨                   2023/10/17              修改内容描述
***********************************************************************/

trigger OpportunityTrigger on Opportunity (after insert, after update, after delete) {

    Set<Id> accountIds = new Set<Id>(); // 用于存储需要更新商机汇总的客户ID

    // 处理商机的插入、更新、删除
    if (Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete) {
        for (Opportunity opp : Trigger.new) {
            accountIds.add(opp.AccountId);
        }
    }

    List<Opportunity> opportunitys = new List<Opportunity>([
        SELECT AccountId
        , Amount
        FROM Opportunity
        WHERE Opportunity.AccountId IN :accountIds AND Opportunity.Amount != null
    ]);
    
    // System.debug(opportunityAmounts);

    // 更新客户记录上的商机汇总字段
    List<Account> updatedAccounts = new List<Account>();
    for (Id accountId : accountIds) {
        Decimal totalPrice = 0.0;
        for (Opportunity opportunity : opportunitys) {
            if (opportunity.AccountId == accountId) {
                totalPrice += Opportunity.amount;
            }
        }
        Account account = new Account(Id = accountId);
        account.Business_opportunity_amount__c = totalPrice;
        updatedAccounts.add(account);
    }

    // 查询商机产品的金额类型
    // Map<Id, AggregateResult> opportunityAmounts = new Map<Id, AggregateResult>([
    //     SELECT Opportunity.AccountId
    //         ,SUM(Amount) totalPrice
    //     FROM Opportunity
    //     WHERE Opportunity.AccountId in :accountIds
    //     GROUP BY Opportunity.AccountId
    // ]);

    // // 更新客户记录上的商机汇总字段
    // List<Account> updatedAccounts = new List<Account>();
    // for (Id accountId : accountIds) {
    //     AggregateResult  accountAmount = opportunityAmounts.get(accountId);
    //     if (accountAmount != null) {
    //         Account account = new Account(Id = accountId);
    //         Decimal totalPrice = (Decimal)accountAmount.get('totalPrice');
    //         account.Business_opportunity_amount__c = totalPrice;
    //         updatedAccounts.add(account);
    //     }
    // }

    // 批量更新客户记录
    if (!updatedAccounts.isEmpty()) {
        update updatedAccounts;
    }
}